package com.app.studyroom;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.view.KeyEvent;

import androidx.appcompat.widget.SwitchCompat;

import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.messageNotice.MessageItem;
import com.app.studyroom.api.model.ssrGet.OpenStatusRequest;
import com.app.studyroom.api.model.ssrGet.OpenStatusResponse;
import com.app.studyroom.api.model.ssrUser.UserUpdateRequest;
import com.app.studyroom.db.UserInfo;
import com.app.studyroom.dialog.CustomSizeDialog;
import com.app.studyroom.peripherals.icCardRead.CardReaderGuard;
import com.app.studyroom.mapper.ClassroomInfoMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdminDashboardActivity extends BaseActivity {

    private ImageView Image_back;
    private Button btnUserControl,btnSeatControl,btnBookingControl,btnAnnouncementControl,btnMessageNotice,btnBindICCard,btnTaskCenter;
    private Button btnSaveSetting;
    private TextView tvCloseApp;
    private SwitchCompat switchApproval;
    private Map<String, Long> userMap = new HashMap<>();

    //关闭app
    private Runnable closeRunnable;
    private boolean isClosing = false;

    //绑定IC卡弹窗
    private CustomSizeDialog bindDialog;
    private TextView tvBindStatus, tvBindCardId;
    private TextView tvUnreadBadge;
    private Spinner spUser;
    Spinner spinnerSleepTimeout,spinnerCurrentClassName;
    EditText editLockPassword;
    private EditText etBindInput;

    //定时刷新
    private final long REFRESH_INTERVAL_MS = 1 * 60 * 1000; // 1分钟
    private final android.os.Handler refreshHandler = new android.os.Handler();

    //设置时间和教室
    private final String[] timeoutOptions = {"30秒", "10分钟", "15分钟", "30分钟", "1小时", "2小时", "永不"};
    private final long[] timeoutValues = {30_000L, 600_000L, 900_000L, 1_800_000L, 3_600_000L, 7_200_000L, -1L};
    private List<String> classroomIds = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_dashboard);

        LinearLayout btnViewStatus = findViewById(R.id.view_all_status);
        btnViewStatus.setOnClickListener(v -> {
            Intent intent = new Intent(this, AdminSeatStatusActivity.class);
            startActivity(intent);
        });

        //初始化控件
        Image_back=findViewById(R.id.ic_back);
        btnUserControl=findViewById(R.id.btnUserControl);
        btnSeatControl=findViewById(R.id.btnSeatControl);
        btnBookingControl=findViewById(R.id.btnBookingControl);
        btnTaskCenter = findViewById(R.id.btnTaskCenter);
        btnAnnouncementControl=findViewById(R.id.btnAnnouncementControl);
        btnMessageNotice = findViewById(R.id.btnMessageNotice);
        btnBindICCard = findViewById(R.id.btnBindICCard);
        btnSaveSetting = findViewById(R.id.btnSaveSetting);
        tvCloseApp = findViewById(R.id.tvCloseApp);
        switchApproval = findViewById(R.id.switchApproval);
        tvUnreadBadge = findViewById(R.id.tvUnreadBadge);
        Image_back.setOnClickListener(v -> onBackPressed());
        initSettingsUI();
        closeRunnable = () -> {
            Toast.makeText(this, "应用已关闭", Toast.LENGTH_SHORT).show();
            finishAffinity();
            System.exit(0);
        };

        //响应
        btnUserControl.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, AdminUserControlActivity.class);
            startActivity(intent);
        });
        btnSeatControl.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, AdminSeatControlActivity.class);
            startActivity(intent);
        });
        btnBookingControl.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, AdminBookingControlActivity.class);
            startActivity(intent);
        });
        btnAnnouncementControl.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, AdminAnnouncementControlActivity.class);
            startActivity(intent);
        });
        btnMessageNotice.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, MessageNoticeActivity.class);
            startActivity(intent);
        });
        btnTaskCenter.setOnClickListener(v -> {
            Intent intent = new Intent(AdminDashboardActivity.this, AdminApprovalTaskActivity.class);
            startActivity(intent);
        });
        btnSaveSetting.setOnClickListener(v -> saveSettings());
        tvCloseApp.setOnLongClickListener(v -> {
            if (!isClosing) {
                isClosing = true;
                tvCloseApp.postDelayed(closeRunnable, 5000); // 长按 5 秒触发
                Toast.makeText(this, "继续长按以关闭应用", Toast.LENGTH_SHORT).show();
            }
            return true;
        });
        tvCloseApp.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    isClosing = false;
                    tvCloseApp.removeCallbacks(closeRunnable);
                    v.performClick();
                    break;
            }
            return false;
        });


        switchApproval.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveApprovalSwitchStatus(isChecked);
        });
        btnBindICCard.setOnClickListener(v -> showBindDialog());

        //预约管理隐藏
        btnBookingControl.setVisibility(ImageView.GONE);
        queryApprovalSwitchStatus();

    }
    @Override
    protected void onPause() {
        super.onPause();
        CardReaderGuard.isReadingCard = false;
        refreshHandler.removeCallbacks(refreshRunnable);
    }
    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadBadge(); // 每次回到界面就刷新未读消息数
        refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL_MS);
    }
    private void queryApprovalSwitchStatus() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getOpenStatus().enqueue(new Callback<ApiResponse<OpenStatusResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<OpenStatusResponse>> call, Response<ApiResponse<OpenStatusResponse>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    OpenStatusResponse status = response.body().getData();
                    boolean isOpen = "true".equalsIgnoreCase(status.open);
                    switchApproval.setChecked(isOpen);
                } else {
                    Toast.makeText(AdminDashboardActivity.this, "获取审批状态失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<OpenStatusResponse>> call, Throwable t) {
                Toast.makeText(AdminDashboardActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void saveApprovalSwitchStatus(boolean isOpen) {
        String openValue = isOpen ? "true" : "false";
        OpenStatusRequest request = new OpenStatusRequest(1, openValue);
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.saveOpenStatus(request).enqueue(new Callback<ApiResponse<OpenStatusResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<OpenStatusResponse>> call, Response<ApiResponse<OpenStatusResponse>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    String message = isOpen ? "审批模式已打开" : "审批模式已关闭";
                    Toast.makeText(AdminDashboardActivity.this, message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AdminDashboardActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<OpenStatusResponse>> call, Throwable t) {
                Toast.makeText(AdminDashboardActivity.this, "提交失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showBindDialog() {
        CardReaderGuard.isReadingCard = true;

        bindDialog = new CustomSizeDialog(this,
                R.layout.diaolg_bind_ic, 0.7f, 0.7f);
        bindDialog.show();

        // 拿控件
        spUser       = bindDialog.findViewById(R.id.spUser);
        tvBindCardId = bindDialog.findViewById(R.id.tvCardId);
        tvBindStatus = bindDialog.findViewById(R.id.tvBindStatus);
        etBindInput  = bindDialog.findViewById(R.id.etCardInput);

        loadUserListForBindDialog(); // 填充 Spinner 学生列表

        etBindInput.requestFocus();
        etBindInput.setInputType(android.text.InputType.TYPE_NULL);
        etBindInput.setShowSoftInputOnFocus(false);

        // 捕获回车，实时显示卡号
        etBindInput.setOnKeyListener((v,k,e)->{
            if(e.getAction()==KeyEvent.ACTION_DOWN &&
                    (k==KeyEvent.KEYCODE_ENTER || k==KeyEvent.KEYCODE_NUMPAD_ENTER)){
                String cid = etBindInput.getText().toString().trim();
                tvBindCardId.setText(cid);
                return true;
            }
            return false;
        });

        // 绑定按钮
        bindDialog.findViewById(R.id.btnBind).setOnClickListener(v -> {
            String cardId = tvBindCardId.getText().toString();
            if(cardId.isEmpty()){
                Toast.makeText(this,"请先刷卡",Toast.LENGTH_SHORT).show();
                return;
            }
            if (cardId.isEmpty()) {
                Toast.makeText(this, "请先刷卡", Toast.LENGTH_SHORT).show();
                return;
            }
            String selected = spUser.getSelectedItem().toString();
            Long userId = userMap.get(selected);
            if (userId == null) {
                Toast.makeText(this, "无法获取选中用户ID", Toast.LENGTH_SHORT).show();
                return;
            }
            tvBindStatus.setText("绑定中…");
            bindUserToCard(userId, cardId);

        });

        // 取消按钮
        bindDialog.findViewById(R.id.btnCancel).setOnClickListener(v -> {
            CardReaderGuard.isReadingCard = false;
            bindDialog.dismiss();
        });
    }
    private void updateUnreadBadge() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) return;

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getMessageList(token).enqueue(new Callback<ApiResponse<List<MessageItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<MessageItem>>> call, Response<ApiResponse<List<MessageItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<MessageItem> list = response.body().getData();
                    long unreadCount = list.stream().filter(m -> m.getStatus() == 0).count();

                    if (unreadCount > 0) {
                        // ✅ 防止数字太大
                        if (unreadCount > 99) {
                            tvUnreadBadge.setText("99+");
                        } else {
                            tvUnreadBadge.setText(String.valueOf(unreadCount));
                        }
                        tvUnreadBadge.setVisibility(View.VISIBLE);
                    } else {
                        tvUnreadBadge.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<MessageItem>>> call, Throwable t) {
                Log.e("Badge", "加载未读数失败", t);
            }
        });
    }
    private void loadUserListForBindDialog() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", "");

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getUserList(token).enqueue(new Callback<ApiResponse<List<UserInfo>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<UserInfo>>> call, Response<ApiResponse<List<UserInfo>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<UserInfo> users = response.body().getData();

                    List<String> displayList = new ArrayList<>();
                    userMap.clear(); // ✅ 清除旧数据，使用类级变量而非新建局部变量

                    for (UserInfo user : users) {
                        String display = user.getUserName() + "（" + user.getUserNumber() + "）";
                        displayList.add(display);
                        userMap.put(display, user.getId()); // ✅ 使用类级 userMap
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AdminDashboardActivity.this,
                            android.R.layout.simple_spinner_item, displayList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spUser.setAdapter(adapter);

                } else {
                    Toast.makeText(AdminDashboardActivity.this, "加载用户失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<UserInfo>>> call, Throwable t) {
                Toast.makeText(AdminDashboardActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void bindUserToCard(Long userId, String cardId) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) {
            Toast.makeText(this, "未登录，无法绑定", Toast.LENGTH_SHORT).show();
            return;
        }

        UserUpdateRequest request = new UserUpdateRequest();
        request.setId(userId);
        request.setIcId(cardId);

        // ✅ 打印请求体信息
        Log.d("IC_BIND", "绑定请求体：userId=" + userId + ", icId=" + cardId);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.userUpdate(token, request).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    tvBindStatus.setText("绑定成功！");
                    Toast.makeText(AdminDashboardActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                    tvBindCardId.setText("");
                    etBindInput.setText("");
                    etBindInput.requestFocus();
                } else {
                    tvBindStatus.setText("绑定失败：" + (response.body() != null ? response.body().getMessage() : "未知错误"));
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                tvBindStatus.setText("绑定失败，网络异常");
                Toast.makeText(AdminDashboardActivity.this, "绑定失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void initSettingsUI() {
        spinnerSleepTimeout = findViewById(R.id.spinnerSleepTimeout);
        editLockPassword = findViewById(R.id.editLockPassword);
        spinnerCurrentClassName = findViewById(R.id.spinnerCurrentClassName);

        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        long currentTimeout = prefs.getLong("sleepTimeoutMillis", 30_000L); // 默认15分钟
        String savedPassword = prefs.getString("lockScreenPassword", "123456");
        String currentClassName = prefs.getString("currentClassName", null);

        // 设置休眠时间 Spinner
        ArrayAdapter<String> timeoutAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, timeoutOptions);
        timeoutAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSleepTimeout.setAdapter(timeoutAdapter);
        int timeoutIndex = 2; // 默认15分钟
        for (int i = 0; i < timeoutValues.length; i++) {
            if (timeoutValues[i] == currentTimeout) {
                timeoutIndex = i;
                break;
            }
        }
        spinnerSleepTimeout.setSelection(timeoutIndex);
        editLockPassword.setText(savedPassword);

        // 构造教室名称列表用于显示
        classroomIds = ClassroomInfoMapper.getClassroomIdList(); // 使用类成员变量
        List<String> classroomNames = new ArrayList<>();
        for (String id : classroomIds) {
            classroomNames.add(ClassroomInfoMapper.getName(id));
        }

        ArrayAdapter<String> classAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, classroomNames);
        classAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCurrentClassName.setAdapter(classAdapter);

        // 根据保存的 classId 反查对应名称并选中
        int classIndex = 0;
        if (currentClassName != null) {
            for (int i = 0; i < classroomNames.size(); i++) {
                if (classroomNames.get(i).equals(currentClassName)) {
                    classIndex = i;
                    break;
                }
            }
        }
        spinnerCurrentClassName.setSelection(classIndex);
    }
    private void saveSettings() {
        if (spinnerSleepTimeout == null || spinnerCurrentClassName == null || editLockPassword == null) return;

        int selectedIndex = spinnerSleepTimeout.getSelectedItemPosition();
        long selectedTimeout = timeoutValues[Math.max(0, Math.min(selectedIndex, timeoutValues.length - 1))];
        String newPassword = editLockPassword.getText().toString().trim();
        String selectedClassName = spinnerCurrentClassName.getSelectedItem().toString();

        // ✅ 添加6位数字校验
        if (!newPassword.matches("\\d{6}")) {
            Toast.makeText(this, "密码必须为6位数字", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        prefs.edit()
                .putLong("sleepTimeoutMillis", selectedTimeout)
                .putString("lockScreenPassword", newPassword)
                .putString("currentClassName", selectedClassName)
                .apply();

        Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
    }
    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            updateUnreadBadge(); // 刷新未读数
            refreshHandler.postDelayed(this, REFRESH_INTERVAL_MS);
        }
    };


}
